<?php
set_time_limit(0);
$filePath = '../uploadfile/download/sps/files';
$packageDir = '../uploadfile/download/sps/package';
$spsfilePath = '../uploadfile/download/sps/ship_files';//sps运单
$spspackageDir = '../uploadfile/download/sps/ship_package';//sps运单
if($_GET['act']=='importexpress'){
    $tpl->display("uploadFile.htm");
    exit;
}
if($_POST['act']=="import" && !empty($_FILES['order_express_no'])){//导入表格生成sps
	require_once '../lib/excel_reader2.php';
	if(!($_FILES['order_express_no']['size']>0)){
		exit('上传文件为空');
	}

	$data = new Spreadsheet_Excel_Reader($_FILES['order_express_no']['tmp_name']);
// 	echo $data->dump(true,true);exit;
	//先找第一行，找出目标字段所在列数
	$order_id_colnum = 0;
	$express_no_colnum = 0;
	for($col=1;$col<=$data->colcount();$col++) {
		$val = $data->val(1,$col);
		if($val=='订单号'){
			$order_id_colnum = $col;
		}
		if($val=='收货人'){
			$express_no_colnum = $col;
		}
	}
	//把目标值放入数组
	$expressNoArr = array();
	if($order_id_colnum>0 && $express_no_colnum>0){
		for($row=2;$row<=$data->rowcount();$row++) {
			$expressNoArr[] = array(
					'order_id'	=>trim($data->val($row,$order_id_colnum)),
					'ship_name'=>trim($data->val($row,$express_no_colnum))//收货人
			);
		}
	}

	foreach ($expressNoArr as $v)
	{
	    $param = "";
		if($v['ship_name']!=''){
            $param = "&ship_name=".urlencode($v['ship_name']);
		}
		
		$sql = "select order_id,shipping_no from ".ORDER." where order_id='{$v['order_id']}' ";
		$db->query($sql);
		$orderInfo = $db->fetchRow();
		if(!empty($orderInfo) && !empty($orderInfo['shipping_no'])){
		    $file_path_temp = '/uploadfile/download/sps/ship_files/';
		    $url = $config['weburl']."/admin/module.php?m=logistics&s=print.php&type=expressprint&isGetContent=1&oid=".$v['order_id'].$param;
		    $filename = $config['webroot'].$file_path_temp.$orderInfo['shipping_no'].'.jpg';
		    try {
		        exec('wkhtmltoimage "'.$url.'" '.$filename);
		    }catch (Exception $e){
		        print_r($e);
		    }
		}
	}
	echo '<script>window.parent.main.document.location.reload();window.parent.DialogManager.close("importexpress");</script>';
	exit;
}


//生成
if($_POST['act'] && $_POST['act']=='createPdf'){
    if(!empty($_POST['order_ids'])){
        $sql = "select order_id,shipping_no from ".ORDER." where order_id in({$_POST['order_ids']})";
        $db->query($sql);
        $ship_no = $db->getRows();
        $shipping_no = array();
        foreach ($ship_no as $v)
        {
            $shipping_no[$v['order_id']] = $v['shipping_no'];
        }
        $order_ids = explode(',', $_POST['order_ids']);
        echo '正在生成，请稍候……<br />';
        $count = count($order_ids);
        foreach ($order_ids as $k=>$oid){
            $oid = trim($oid);
            echo '正在生成第'.($k+1).'/'.$count.'个<br />';
            
            $file_path_temp = '/uploadfile/download/sps/files/';
            if($_POST['op']=='生成小票'){
                $url = $config['weburl']."/admin/module.php?m=product&s=sps_bill_show.php&order_id=".$oid;
            }elseif($_POST['op']=='生成sps运单'){
                $file_path_temp = '/uploadfile/download/sps/ship_files/';
                $url = $config['weburl']."/admin/module.php?m=logistics&s=print.php&type=expressprint&isGetContent=1&oid=".$oid;
            }else{
                $url = $config['weburl']."/admin/module.php?m=product&s=sps_bill_show.php&order_id=".$oid;
            }
            if($shipping_no[$oid]){
                $filename = $config['webroot'].$file_path_temp.$shipping_no[$oid].'.jpg';
                try {
                    exec('wkhtmltoimage "'.$url.'" '.$filename);
                }catch (Exception $e){
                    print_r($e);
                }
            }else{
                echo '订单:'.$oid."无运单号";
            }
        }
        echo '全部完成';
        
        msg('?m=product&s=sps_bill.php');//201509120848546002,201509120947583537,201509071202380972
    }
}

//打包
if($_GET['act'] && $_GET['act']=='package'){
    if($_GET['type']=='tip'){
        $res = zipDir($filePath,$packageDir."/".date('YmdHis').'-'.rand(1000,9999).".zip");
        
        if($res){//打包完成后清空文件夹
            deldir($filePath);
        }
    }
    if($_GET['type']=='sps'){
        $res = zipDir($spsfilePath,$spspackageDir."/".date('YmdHis').'-'.rand(1000,9999).".zip");
    
        if($res){//打包完成后清空文件夹
            deldir($spsfilePath);
        }
    }
}

//小票打包文件夹是否为空
$is_sps_files = dir_is_empty($filePath);
$packageError = $is_sps_files?1:0;

//sps运单打包文件夹是否为空
$is_sps_files = dir_is_empty($spsfilePath);
$spsPackageError = $is_sps_files?1:0;


if(!$_GET['file_type']){
    $_GET['file_type'] = 'all';
}
//可下载包列表
if($_GET['file_type']=='all'){
    $list = array();//发票
    if($handle = opendir($packageDir)){
        while($item = readdir($handle)){
            if ($item != '.' && $item != '..'){
                $ctime = filemtime($packageDir.'/'.$item);
                $list[] = array(
                        'name'=>$item,
                        'type'=>'发票',
                        'link'=>$packageDir.'/'.$item,
                        'create_time'=>$ctime
                    );
            }
        }
    }
    
    $list = arraySortByField($list,'create_time','desc');
    
    $spslist = array();//sps运单
    if($handle = opendir($spspackageDir)){
        while($item1 = readdir($handle)){
            if ($item1 != '.' && $item1 != '..'){
                $ctime = filemtime($spspackageDir.'/'.$item1);
                $spslist[] = array(
                    'name'=>$item1,
                    'type'=>'sps运单',
                    'link'=>$spspackageDir.'/'.$item1,
                    'create_time'=>$ctime
                );
            }
        }
    }
    
    $spslist = arraySortByField($spslist,'create_time','desc');
    
    $list = array_merge($list,$spslist);
}elseif ($_GET['file_type']=='tip'){
    $list = array();//发票
    if($handle = opendir($packageDir)){
        while($item = readdir($handle)){
            if ($item != '.' && $item != '..'){
                $ctime = filemtime($packageDir.'/'.$item);
                $list[] = array(
                    'name'=>$item,
                    'type'=>'发票',
                    'link'=>$packageDir.'/'.$item,
                    'create_time'=>$ctime
                );
            }
        }
    }
    
    $list = arraySortByField($list,'create_time','desc');
}elseif ($_GET['file_type']=='sps'){
    $spslist = array();//sps运单
    if($handle = opendir($spspackageDir)){
        while($item1 = readdir($handle)){
            if ($item1 != '.' && $item1 != '..'){
                $ctime = filemtime($spspackageDir.'/'.$item1);
                $spslist[] = array(
                    'name'=>$item1,
                    'type'=>'sps运单',
                    'link'=>$spspackageDir.'/'.$item1,
                    'create_time'=>$ctime
                );
            }
        }
    }
    
    $spslist = arraySortByField($spslist,'create_time','desc');
    
    $list = $spslist;
}
if($_GET['p_stime'] || $_GET['p_etime']){
    $list_temp = array();
    $p_stime = strtotime($_GET['p_stime']);
    $p_etime = strtotime($_GET['p_etime']);
    foreach ($list as $val)
    {
        if($_GET['p_stime'] && !$_GET['p_etime']) {
            if($val['create_time']>="{$p_stime}"){
                $list_temp[] = $val;
            }
        } elseif(!$_GET['p_stime'] && $_GET['p_etime']) {
            if($val['create_time']<="{$p_etime}"){
                $list_temp[] = $val;
            }
        } else {
            if($val['create_time']>="{$p_stime}" && $val['create_time']<="{$p_etime}"){
                $list_temp[] = $val;
            }
        }
    }
    $list = $list_temp;
}

$tpl->assign('packageError',$packageError);
$tpl->assign('spsPackageError',$spsPackageError);
$tpl->assign('list',$list);
$tpl->display('sps_bill.htm');
?>